<template>
  <div class="app-container">
    <div class="filter-container">
      <el-button class="filter-item" style="margin-left: 10px;" type="primary" icon="el-icon-edit" @click="handleCreate">增加</el-button>
      <el-input v-model="listQuery.title" placeholder="请输入名称" style="width:250px;" class="filter-item" @keyup.enter.native="handleFilter" />
      <!--  <el-select v-model="listQuery.importance" placeholder="Imp" clearable style="width: 90px" class="filter-item">
        <el-option v-for="item in importanceOptions" :key="item" :label="item" :value="item" />
      </el-select>
      <el-select v-model="listQuery.type" placeholder="Type" clearable class="filter-item" style="width: 130px">
        <el-option v-for="item in calendarTypeOptions" :key="item.key" :label="item.display_name+'('+item.key+')'" :value="item.key" />
      </el-select>
      <el-select v-model="listQuery.sort" style="width: 140px" class="filter-item" @change="handleFilter">
        <el-option v-for="item in sortOptions" :key="item.key" :label="item.label" :value="item.key" />
      </el-select> -->
      <el-button v-waves class="filter-item" type="primary" icon="el-icon-search" @click="handleFilter">搜索</el-button>

      <el-button v-waves :loading="downloadLoading" class="filter-item" type="primary" icon="el-icon-download" @click="handleDownload">导出</el-button>
      <!--  <el-checkbox v-model="showReviewer" class="filter-item" style="margin-left:15px;" @change="tableKey=tableKey+1">
        reviewer
      </el-checkbox> -->
    </div>

    <el-table :key="tableKey" v-loading="listLoading" :data="list" border fit highlight-current-row style="width: 100%;" @sort-change="sortChange">
      <el-table-column label="ID"  width="60"    prop="id" sortable="custom" align="center" :class-name="getSortClass('id')">
        <template slot-scope="{ row }">
          <span>{{row.id}}</span>
        </template>
      </el-table-column>
      <el-table-column label="图片" width="80"   align="center">
        <template slot-scope="{row}">
          <span>
            <el-image :src="$baseUrl+row.pic" lazy class="img50" fit="cover">
              <div slot="placeholder" class="image-slot">
                      <i class="el-icon-loading" />
              </div>
              <div slot="error" class="image-slot"><i class="el-icon-picture-outline"></i></div>
            </el-image>
          </span>
        </template>
      </el-table-column>
      <el-table-column label="名称" align="center">
        <template slot-scope="{ row }">
          <span>{{ row.name }}</span>
        </template>
      </el-table-column>
      <el-table-column label="简介" align="center">
        <template slot-scope="{ row }">
          <span>{{ row.intro }}</span>
        </template>
      </el-table-column>

      <el-table-column label="操作" align="center" width="230" class-name="small-padding fixed-width">
        <template slot-scope="{ row, $index }">
          <el-button type="primary" size="mini" @click="handleUpdate(row)">修改</el-button>
          <!-- <el-button v-if="row.status!='published'" size="mini" type="success" @click="handleModifyStatus(row,'published')">
            Publish
          </el-button>
          <el-button  size="mini" type="success"  @click="handleModifyStatus(row,'draft')">
           章节
          </el-button>
           -->
          <el-button v-if="row.status != 'deleted'" size="mini" type="danger" @click="handleDelete(row, $index)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total > 0" :total="total" :page.sync="listQuery.pageNo" :limit.sync="listQuery.pageSize" @pagination="getList" />

    <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible">
      <el-form ref="postForm" :rules="rules" :model="postForm" label-position="left" label-width="70px" style="width: 400px; margin-left:50px;">
        <!-- <el-form-item label="Date" prop="timestamp">
          <el-date-picker v-model="temp.timestamp" type="datetime" placeholder="Please pick a date" />
        </el-form-item> -->
        <el-form-item label="名称" prop="name"><el-input v-model="postForm.name" /></el-form-item>
        <el-form-item label="图片" >
          <el-upload :limit="imgUploadLimit" :action="imgUploadUrl" :file-list="fileList"
            list-type="picture-card"
            :headers = "headers"
            :on-preview="handlePictureCardPreview"
            :on-remove="handleUploadRemove"
            :on-success="handleUploadSuccess"
            :on-exceed="handleUploadExceed"
            :on-error="handleUploadError" >
            <i class="el-icon-plus"></i>
            <div class="el-upload__tip" slot="tip">1、只能上传jpg/png文件，且不超过500kb</div>
          </el-upload>
          <el-dialog :visible.sync="uploadDialogVisible">
            <img width="100%" :src="uploadDialogImageUrl" alt="">
          </el-dialog>
        </el-form-item>
        <!-- <el-form-item label="上级" prop="type">
          <el-select v-model="temp.type" class="filter-item" placeholder="Please select">
            <el-option v-for="item in calendarTypeOptions" :key="item.key" :label="item.display_name" :value="item.key" />
          </el-select>
        </el-form-item> -->
        <!-- <el-form-item label="Status">
          <el-select v-model="temp.status" class="filter-item" placeholder="Please select">
            <el-option v-for="item in statusOptions" :key="item" :label="item" :value="item" />
          </el-select>
        </el-form-item> -->
        <!-- <el-form-item label="Imp">
          <el-rate v-model="temp.importance" :colors="['#99A9BF', '#F7BA2A', '#FF9900']" :max="3" style="margin-top:8px;" />
        </el-form-item> -->
        <el-form-item label="简介"><el-input v-model="postForm.intro" :autosize="{ minRows: 2, maxRows: 4 }" type="textarea" placeholder="请输入分类简介" /></el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取消</el-button>
        <el-button type="primary" @click="dialogStatus === 'create' ? createData() : updateData()">提交</el-button>
      </div>
    </el-dialog>

    <el-dialog :visible.sync="dialogPvVisible" title="Reading statistics">
      <el-table :data="pvData" border fit highlight-current-row style="width: 100%">
        <el-table-column prop="key" label="Channel" />
        <el-table-column prop="pv" label="Pv" />
      </el-table>
      <span slot="footer" class="dialog-footer"><el-button type="primary" @click="dialogPvVisible = false">提交</el-button></span>
    </el-dialog>
  </div>
</template>

<script>
import API from '@/api/grade';
import waves from '@/directive/waves'; // waves directive
import { parseTime,param2Obj } from '@/utils';
import Pagination from '@/components/Pagination'; // secondary package based on el-pagination
import imageAPI from '@/api/image'
import { getToken } from '@/utils/auth'

const defaultForm = {
    id: undefined,
    name: '',
    intro: '',
    pic:'',
    timestamp: new Date()
}

export default {
  name: 'grade',
  components: { Pagination },
  directives: { waves },
  filters: {
    statusFilter(status) {
      const statusMap = {
        published: 'success',
        draft: 'info',
        deleted: 'danger'
      };
      return statusMap[status];
    },
    typeFilter(type) {}
  },
  data() {
    return {
      postForm: Object.assign({}, defaultForm),
      tableKey: 0,
      list: null,
      total: 0,
      listLoading: true,
      listQuery: {
        pageNo: 1,
        pageSize: 10,
        name: undefined,
        sort: '+id'
      },
      importanceOptions: [],

      sortOptions: [{ label: 'ID Ascending', key: '+id' }, { label: 'ID Descending', key: '-id' }],
      statusOptions: ['published', 'draft', 'deleted'],
      showReviewer: false,
      dialogFormVisible: false,
      dialogStatus: '',
      textMap: {
        update: '修改 ',
        create: '增加'
      },
      dialogPvVisible: false,
      pvData: [],
      rules: {
        name: [{ required: true, message: '名称必填', trigger: 'blur' }]    
      },
      downloadLoading: false,
      fileList:[],//图片上传相关
      uploadDialogImageUrl: '',
      uploadDialogVisible: false,
      imgUploadLimit:1,
      imgUploadUrl:this.$baseUrl+"/api/imgupload",
      headers:{
        Authorization: "Bearer "+ getToken()  //从cookie里获取token，并赋值  Authorization ，而不是token
      }
    };
  },
  created() {
    this.getList();
  },
  methods: {
    getList() {
      this.listLoading = true;
      API.fetchList(this.listQuery).then(response => {
        this.list = response.data.items;
        this.total = response.data.total;

        // Just to simulate the time of the request
        setTimeout(() => {
          this.listLoading = false;
        }, 10);
      });
    },
    handleFilter() {
      this.listQuery.page = 1;
      this.getList();
    },
    handleModifyStatus(row, status) {
      this.$message({
        message: '操作成功',
        type: 'success'
      });
      row.status = status;
    },
    sortChange(data) {
      const { prop, order } = data;
      if (prop === 'id') {
        this.sortByID(order);
      }
    },
    sortByID(order) {
      if (order === 'ascending') {
        this.listQuery.sort = '+id';
      } else {
        this.listQuery.sort = '-id';
      }
      this.handleFilter();
    },
    resetTemp() {
      this.postForm=Object.assign({}, defaultForm)
    },
    handleCreate() {
      this.resetTemp();
      this.dialogStatus = 'create';
      this.dialogFormVisible = true;
      this.$nextTick(() => {
        this.$refs['postForm'].clearValidate();
      });
    },
    createData() {
      this.$refs['postForm'].validate(valid => {
        if (valid) {
          API.add(this.postForm).then(() => {
            //this.list.unshift(this.temp)
            this.getList();
            this.dialogFormVisible = false;
            this.$notify({
              title: '提示',
              message: '添加成功！',
              type: 'success',
              duration: 2000
            });
          });
        }
      });
    },
    handleUpdate(row) {
      this.postForm = Object.assign({}, row); // copy obj
      this.postForm.pic&&(this.fileList=[{name: this.postForm.pic, url:this.$baseUrl+this.postForm.pic }])
      this.postForm.timestamp = new Date(this.postForm.timestamp);
      this.dialogStatus = 'update';
      this.dialogFormVisible = true;
      this.$nextTick(() => {
        this.$refs['postForm'].clearValidate();
      });
    },
    updateData() {
      this.$refs['postForm'].validate(valid => {
        if (valid) {
          const tempData = Object.assign({}, this.postForm);
          tempData.timestamp = +new Date(tempData.timestamp); // change Thu Nov 30 2017 16:41:05 GMT+0800 (CST) to 1512031311464
          API.update(tempData).then(() => {
            const index = this.list.findIndex(v => v.id === this.postForm.id);
            this.list.splice(index, 1, this.postForm);
            this.dialogFormVisible = false;
            this.$notify({
              title: '提示',
              message: '修改成功',
              type: 'success',
              duration: 2000
            });
          });
        }
      });
    },
    handleDelete(row, index) {
      this.$confirm('确认删除吗?', '提醒', { confirmButtonText: '确定', cancelButtonText: '取消', type: 'warning' })
        .then(() => {
          //点击确定的操作(调用接口)
          API.delete(row.id).then(() => {
            this.$notify({
              title: '提示',
              message: '删除成功！',
              type: 'success',
              duration: 2000
            });
            this.list.splice(index, 1);
          });
        })
        .catch(() => {}); //几点取消的提醒
    },
    handleFetchPv(pv) {
      // fetchPv(pv).then(response => {
      //   this.pvData = response.data.pvData
      //   this.dialogPvVisible = true
      // })
    },
    handleDownload() {
      this.downloadLoading = true;
      import('@/vendor/Export2Excel').then(excel => {
        const tHeader = ['id', 'name', 'intro'];
        const filterVal = ['id', 'name', 'intro'];
        const data = this.formatJson(filterVal);
        excel.export_json_to_excel({
          header: tHeader,
          data,
          filename: 'grade-list'
        });
        this.downloadLoading = false;
      });
    },
    formatJson(filterVal) {
      return this.list.map(v =>
        filterVal.map(j => {
          if (j === 'timestamp') {
            return parseTime(v[j]);
          } else {
            return v[j];
          }
        })
      );
    },
    getSortClass: function(key) {
      const sort = this.listQuery.sort;
      return sort === `+${key}` ? 'ascending' : 'descending';
    },
    handleUploadRemove(file, fileList) {
       //console.log(file, fileList);
       if(file.id){
         imageAPI.delete(file.id)
       }else{
         var params=param2Obj(file.url)
         if(params.id){
           imageAPI.delete(params.id)
         }else{
           this.$message.warning("未能从数据库删除此图片，未指定id或者此图片正在使用");
         }
       }
       this.postForm.pic=''
    },
    handleUploadSuccess(response, file, fileList) {
       //console.log(file, fileList);
       if(!response.status){
          this.$message.error(response.msg);
          fileList.pop()
          return
       }
       file.id=response.data.id
       this.postForm.pic=response.data.path+"?id="+ file.id
    },
    handlePictureCardPreview(file) {
      this.uploadDialogImageUrl = file.url;
      this.uploadDialogVisible = true;
    },
    handleUploadExceed(files, fileList){
      this.$message.warning(`当前限制选择 ${this.imgUploadLimit} 个文件，本次选择了 ${files.length} 个文件，共选择了 ${files.length + fileList.length} 个文件`);
    },
    handleUploadError(err, file, fileList){
       this.$message.error(`上传文件${file.name}失败`+err);
    }
  }
};
</script>
